<!--
 * @Author: wjk
 * @Date: 2019-12-31 15:40:51
 * @LastEditors: wjk
 * @LastEditTime: 2020-12-15 16:55:03
 * @description: file content
 -->
<template>
  <base-page-view :class-name="'material-search-container ' + (showResult ? 'list-background':'')">
    <view class="sticky-wrap">
      <view class="search-block">
        <view class="search-left">
          <search-bar v-if="!authFlag" ref="search-bar" :keyword="listQuery.searchKey" :placeholder="'输入关键词搜索'" background="#F5F5F6" @change="keyChange" @clear="keyClear" @search="search"></search-bar>
        </view>
        <view class="back-btn" @click="backClick">取消</view>
      </view>
    </view>

    <template v-if="listQuery.searchKey">
      <!-- 搜索结果 -->
      <template v-if="showResult">
        <view>
          <article-list ref="articleList" :article-list="list" />
          <base-list-state :list-length="listLength" :list-query="{page_no: listQuery.pageNo, page_size: listQuery.pageSize}" :list-state="listState" :list-empty="listEmpty" />
        </view>
      </template>
    </template>
    <view v-else class="history-list">
      <!-- 搜索历史 -->
      <view v-if="keyword.history.length" class="keyword-block history">
        <view class="block-title">
          <view class="sub-item">历史搜索</view>
          <image class="icon" src="/static/images/icon/icon_delete.png" mode="aspectFit" @click="clearHistory" />
        </view>
        <view class="block-content">
          <view v-for="(item, index) in keyword.history" :key="index" class="keyword-item" @click="keywordClick(item, 'history')">{{ item }}</view>
        </view>
      </view>
      <!-- 热门搜索 -->
      <view v-if="keyword.hot.length" class="keyword-block hot">
        <view class="block-title">
          <view class="sub-item">热门搜索</view>
        </view>
        <view class="block-content">
          <view v-for="(item, index) in keyword.hot" :key="index" class="keyword-item" @click="keywordClick(item, 'hot')">
            {{ item }}
          </view>
        </view>
      </view>

    </view>
    <!-- <recommend ref="recommend" v-if="(list && list.length === 0 && listState.loading === false) || !showResult" /> -->
    <recommend v-if="(list && list.length === 0 && listState.loading === false) || !showResult" ref="recommend" />

  </base-page-view>
</template>

<script>
import ArticleList from './components/article-list'
import searchBar from '@/components/searchBar/index'
import recommend from './components/recommend.vue'
import { debounce } from '@/utils/tools'
import './search.scss'
export default {
  components: {
    searchBar,
    recommend,
    ArticleList
  },
  data() {
    return {
      keyword: {
        history: [],
        hot: [],
        suggest: []
      },
      refreshFlag: false,
      listQuery: {
        searchKey: '',
        sort: 'DESC',
        sortField: 'COMPOSITE',
        pageNo: 1,
        pageSize: 10
      },
      list: [],
      listState: {
        loading: false,
        more: true
      },
      listEmpty: { type: 'empty_list', text: '暂无数据' },
      showResult: false,
      authFlag: false
    }
  },
  computed: {
    listLength() { // 由于微信小程序无法自动更新base-list-state组件,故采用computed
      return this.list.length
    }
  },
  created() {
  },
  onLoad(option) {
    this.listQuery = {
      searchKey: '',
      sort: 'DESC',
      sortField: 'COMPOSITE',
      pageNo: 1,
      pageSize: 10
    }
    this.listState = {
      loading: false,
      more: true
    }
    this.list = []
    this.fetchData()
  },
  onShow() {
    if (this.authFlag) {
      this.authFlag = false
      this.fetchGoodsData(true)
    }
  },
  onPullDownRefresh() {
    this.listQuery.pageNo = 1
    this.fetchGoodsData(true)
  },
  onReachBottom: debounce(function() {
    if (!this.showResult && this.$refs.recommend) {
      this.$refs.recommend.loadMore()
    } else if (this.listState.more && !this.listState.loading) {
      this.listQuery.pageNo++
      this.fetchGoodsData()
    }
  }, 500),
  methods: {
    async fetchData() {
      const res = await this.$api.materialApi.searchKey()
      if (res.success && res.data) {
        this.keyword.hot = res.data.hotSearchKeys || []
        this.keyword.history = res.data.searchHistorys || []
      }
    },
    clearHistory() {
      this.$gc.$message({
        content: '删除后无法恢复哦, 确认删除吗?',
        title: '温馨提示',
        confirmText: '确认删除',
        align: 'center',
        confirm: async() => {
          this.$api.materialApi.searchDelete()
          this.keyword.history = []
        }
      })
    },
    keyChange(value) {
      this.listQuery.searchKey = value
    },
    keyClear() {
      this.listQuery.searchKey = ''
      this.showResult = false
    },
    keywordClick(value, type) {
      this.listQuery.searchKey = value
      this.$refs['search-bar'].setValue(value)
      this.search(type)
    },
    async search(type) {
      if (this.listQuery.searchKey !== '') {
        this.list = []
        this.listQuery.pageNo = 1
        this.listState.more = true
        await this.fetchGoodsData()
        this.saveSearchHistory(this.listQuery.searchKey)
        this.showResult = true
      } else {
        uni.showToast({
          title: '搜索不能为空',
          icon: 'none',
          duration: 2000
        })
      }
      // this.listQuery.searchKey = value
    },
    async fetchGoodsData(flag) {
      this.refreshFlag = !!flag
      this.listState.loading = true
      const res = await this.$api.materialApi.searchList(this.listQuery)
      if (this.listQuery.pageNo === 1) {
        this.list = []
      }
      if (res.success && res.data) {
        this.list = this.list.concat(res.data)
        this.listState.more = this.listQuery.pageNo < res.data.length
      }

      setTimeout(() => {
        this.listState.loading = false
        this.refreshFlag = false
        uni.stopPullDownRefresh()
      }, 500)
    },
    saveSearchHistory(value) {
      this.fetchData()
      // if (!this.keyword.history.includes(value)) {
      //   this.keyword.history.push(value)
      // }
    },
    backClick() {
      uni.navigateBack()
    }
  }
}
</script>
